package com.jinyu.jyly.net.api;


import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.jinyu.jyly.bean.AllBean;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

import okhttp3.MediaType;
import okhttp3.ResponseBody;
import retrofit2.Converter;

public class GsonRequestBodyConverter<T> implements Converter<ResponseBody, T> {
    private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");
    private static final Charset UTF_8 = Charset.forName("UTF-8");
    private final Gson gson;

    private final TypeAdapter<T> adapte;

    public GsonRequestBodyConverter(Gson gson, TypeAdapter<T> adapte) {
        this.gson = gson;
        this.adapte = adapte;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        String response = value.string();
        //先将返回的json数据解析到Response中，如果code==200，则解析到我们的实体基类中，否则抛异常
        AllBean allBean = gson.fromJson(response, AllBean.class);
        int code = allBean.getStatus();

        if (code != 200) {
            if (code != 0) {
                value.close();
                response = gson.toJson(allBean);
            }
        }

        MediaType mediaType = value.contentType();
        Charset charset = mediaType != null ? mediaType.charset(UTF_8) : UTF_8;
        ByteArrayInputStream inputStream = new ByteArrayInputStream(response.getBytes());
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, charset);
        JsonReader jsonReader = gson.newJsonReader(inputStreamReader);
        try {
            return adapte.read(jsonReader);
        } finally {
            value.close();
        }
    }


}
